package com.jichangxiu.framework.entity.bo;

import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.common.constant.Constants;
import com.jichangxiu.framework.proxy.DynamicSourceProxy;
import com.jichangxiu.framework.utils.DynamicUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
public class DynamicSource extends AbstractRoutingDataSource {

    // 重写方法，获取的是动态代理对象
    @Override
    public Connection getConnection() {
        return (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                new Class[]{Connection.class},
                new DynamicSourceProxy(this));
    }

    // 获取真正的 Connection 连接对象(其实也是数据源厂商实现的代码连接)
    public Connection getRealConnection() throws SQLException {
        return super.getConnection();
    }

    @Override
    public Object determineCurrentLookupKey() {
        String currentSource = DynamicUtils.currentSource();
        if (ObjectUtil.isEmpty(currentSource))
            currentSource = Constants.DEFAULT_DATA_SOURCE;
        return currentSource;
    }

    @Override
    public DataSource determineTargetDataSource() {
        return super.determineTargetDataSource();
    }

}
